// import { toast, loading} from "@/assets/utils/toast.js"

const apiUrl = import.meta.env.DEV ?
  // `https://dev-api.ctzwryh.com/api` :
  `https://test-api.ctzwryh.com/api` :
  `https://api.ctzwryh.com`
  
export const uploadUrl = apiUrl + '/resource/oss/appUpload'

const http = (method, url, data) => {
  const options = {
    method: method,
    url: apiUrl + url,
    data: data,
    header: {
      'content-type':
        method == 'GET'
          ? 'application/x-www-form-urlencoded'
          : 'application/json',
      Authorization: `Bearer ${uni.getStorageSync('token')}`, //自定义请求头信息
    },
  }
  $toast.loading(true)
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: res => {
        if (res.data.code == 200) {
          resolve(res.data)
        } else {
          if (res.data.code == 401) {
            // 登录验证报错
            backLoginPage()
            $toast.msg({
              title: '登录失败，请重新登录',
              icon: 'none',
              duration: 1500,
            })
          } else {
            $toast.msg({
              title: res?.data?.msg || '操作失败',
              icon: 'none',
              duration: 1500,
            })
          }
          reject(res)
        }
      },
      fail: res => {
        $toast.msg({
          title: res?.data?.msg || '操作失败',
          icon: 'error',
          duration: 1500,
        })
        reject(res)
      },
      complete: () => {
        $toast.loading(false)
      },
    })
  })
}

export function get(url, data) {
  return http('GET', url, data)
}

export function post(url, data) {
  return http('POST', url, data)
}

export function put(url, data) {
  return http('PUT', url, data)
}

export function del(url, data) {
  return http('DELETE', url, data)
}

export function upload(files) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadUrl,
      files: files, // [{ name: 'file1', uri: 'path/xxx.jpg' }]
      header: { "Content-Type": "multipart/form-data" },
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

const backLoginPage = () => {
  // 登出到登录页
  uni.removeStorage({
    key: 'token',
  })
  uni.removeStorage({
    key: 'userInfo',
  })
  uni.reLaunch({
    url: '/pages/login/index',
  })
}